package com.shop.controller;

import com.shop.constant.UsersConstant;
import com.shop.pojo.ums.Ums_Member;
import com.shop.service.Ums_Member_Service;
import com.shop.token.JwtUtils;
import com.shop.token.R;
import com.shop.token.SystemConstant;
import com.shop.token.JwtUtils;
import com.shop.token.R;
import com.shop.token.SystemConstant;
import com.shop.service.Ums_Member_Service;
import com.shop.utils.VerifyCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/users")
public class UsersController {
    @Autowired
    private Ums_Member_Service ums_member_service;

    @PostMapping("/login")
    public Map<String,Object> getlogin(String username, String password, String code, HttpSession session, HttpServletRequest request){
        System.out.println("账号"+username+"密码"+password+"验证码"+code);
        String validCode = (String) session.getAttribute("validCode");
        System.out.println("delaid:"+validCode);
        Ums_Member usersByParam = ums_member_service.getUsersByParam(username, password);
        Map<String,Object> map=new HashMap<String, Object>();
        map.put("users",usersByParam);
//        if(!validCode.toLowerCase().equals(code.toLowerCase())||!validCode.toUpperCase().equals(code.toUpperCase())){
//            //这里将验证码和传来的验证码都转成小写或者大写来判断
//            map.put("r", R.error(501,"验证码有误"));
//        }
//       else
            if(usersByParam!=null){
            String jwt = JwtUtils.createJWT(String.valueOf(usersByParam.getId()), usersByParam.getNickname(), SystemConstant.JWT_TTL);
            map.put("token",jwt);
            map.put("r", R.ok(200,"success"));
            session.setAttribute(UsersConstant.LOGIN_USERS,usersByParam);
            Ums_Member userNameSession =(Ums_Member) session.getAttribute(UsersConstant.LOGIN_USERS);
            System.out.println(userNameSession);
        } else{
            map.put("r", R.error(500,"用户名或密码输入有误"));
        }



        return map;
    }
    //验证码
    @GetMapping("/code")
    public Object getVerifyCode(HttpServletResponse response, HttpServletRequest request){
        HttpSession session=request.getSession();
        String validCode = VerifyCode.getValidCode(response);//图片通过response响应出去
        System.out.println(validCode);
        session.setAttribute("validCode",validCode);

        return null;
    }


}
